<?php
namespace Home\Controller;
use Think\Controller;
class IndexController extends CommonController {
    public function index(){

    	

    	if(isset($_GET["echostr"])){

    		$echoStr = $_GET["echostr"];
	        //valid signature , option
	        if($this->checkSignature()){
	        	echo $echoStr;
	        	exit;
	        }

    	}else{

    		$this->responseMsg();

    	}

        
    }

    public function responseMsg()
    {
		//get post data, May be due to the different environments
		$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

		$this->log($postStr);

      	//extract post data
		if (!empty($postStr)){
                /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
                   the best way is to check the validity of xml by yourself */
                libxml_disable_entity_loader(true);
              	$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);

              	// $this->log("有人来了");

              	switch ($postObj->MsgType) {
              		case "event":
              			$this->responsEvent($postObj);
              		case 'text':
              			$this->responsText($postObj);
              			break;
              		case 'image':
              			$this->responsImage($postObj);
              			break;
              		case 'voice':
              			$this->responsVoice($postObj);
              			break;
              		case 'video':
              			$this->responsVideo($postObj);
              			break;
              		default:
              			$this->other($postObj);
              			break;
              	}


        }else {
        	echo "";
        	exit;
        }
    }
    public function responsEvent($postObj)
    {
    	if($postObj->Event=='subscribe'){
    		$fromUsername = $postObj->FromUserName;
        	$toUsername = $postObj->ToUserName;
        $time = time();
        $textTpl = "<xml>
					<ToUserName><![CDATA[%s]]></ToUserName>
					<FromUserName><![CDATA[%s]]></FromUserName>
					<CreateTime>%s</CreateTime>
					<MsgType><![CDATA[%s]]></MsgType>
					<Content><![CDATA[%s]]></Content>
					<FuncFlag>0</FuncFlag>
					</xml>";             
		if(true)
        {
      		$msgType = "text";
        	$contentStr = "欢迎关注XXX";
        	$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
        	echo $resultStr;
        }else{
        	echo "Input something...";
        }
    	}
    	// $this->log(var_export($postObj,true));
    }
    public function responsText($postObj)
    {
    	$fromUsername = $postObj->FromUserName;
        $toUsername = $postObj->ToUserName;
        $keyword = trim($postObj->Content);

        $data = $this->wCurl($keyword,$fromUsername);

        // $this->log($data);

        if($data['code']=='100000'){
	        $time = time();
	        $textTpl = "<xml>
						<ToUserName><![CDATA[%s]]></ToUserName>
						<FromUserName><![CDATA[%s]]></FromUserName>
						<CreateTime>%s</CreateTime>
						<MsgType><![CDATA[%s]]></MsgType>
						<Content><![CDATA[%s]]></Content>
						<FuncFlag>0</FuncFlag>
						</xml>";             
			if(!empty( $keyword ))
	        {
	      		$msgType = "text";
	        	$contentStr = $data['text'];
	        	$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
	        	echo $resultStr;
	        }else{
	        	echo "Input something...";
	        }

        }elseif($data['code']=='302000'){
        	
        	$this->responNews($postObj,$data['list']);
        }

    }

    public function responNews($postObj,$news)
    {

    	$news = array_slice($news,0,8);
    	$count = count($news);

    	$fromUsername = $postObj->FromUserName;
        $toUsername = $postObj->ToUserName;
        $time = time();


        $newTpl = "";
        foreach ($news as $new) {
        	$newTpl .= "<item>
			<Title><![CDATA[".$new['article']."]]></Title>
			<Description><![CDATA[".$new['source']."]]></Description>
			<PicUrl><![CDATA[".$new['icon']."]]></PicUrl>
			<Url><![CDATA[".$new['detailurl']."]]></Url>
			</item>";
        }



        $textTpl = "<xml>
			<ToUserName><![CDATA[".$fromUsername."]]></ToUserName>
			<FromUserName><![CDATA[".$toUsername."]]></FromUserName>
			<CreateTime>".$time."</CreateTime>
			<MsgType><![CDATA[news]]></MsgType>
			<ArticleCount>".$count."</ArticleCount>
			<Articles>
			".$newTpl."
			</Articles>
			</xml>";


			// $this->log($textTpl);
			

   //      	$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time,$count);





        	echo $textTpl;
      
    }

    public function responsImage($postObj)
    {
    	$fromUsername = $postObj->FromUserName;
        $toUsername = $postObj->ToUserName;
        $MediaId = trim($postObj->MediaId);
        $time = time();
        $textTpl = "<xml>
			<ToUserName><![CDATA[%s]]></ToUserName>
			<FromUserName><![CDATA[%s]]></FromUserName>
			<CreateTime>%s</CreateTime>
			<MsgType><![CDATA[%s]]></MsgType>
			<Image>
			<MediaId><![CDATA[%s]]></MediaId>
			</Image>
			</xml>";             
		if(!empty( $MediaId ))
        {
      		$msgType = "image";
        	$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $MediaId);
        	echo $resultStr;
        }else{
        	echo "Input something...";
        }

    }

    public function other($postObj)
    {
    	$fromUsername = $postObj->FromUserName;
        $toUsername = $postObj->ToUserName;
        $keyword = trim($postObj->Content);
        $time = time();
        $textTpl = "<xml>
					<ToUserName><![CDATA[%s]]></ToUserName>
					<FromUserName><![CDATA[%s]]></FromUserName>
					<CreateTime>%s</CreateTime>
					<MsgType><![CDATA[%s]]></MsgType>
					<Content><![CDATA[%s]]></Content>
					<FuncFlag>0</FuncFlag>
					</xml>";             
		if(!empty( $keyword ))
        {
      		$msgType = "text";
        	$contentStr = "我不知道你发的类型是什么";
        	$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
        	echo $resultStr;
        }else{
        	echo "Input something...";
        }
    }


    private function checkSignature()
	{
        // you must define TOKEN by yourself
        if (!defined("TOKEN")) {
            throw new Exception('TOKEN is not defined!');
        }

        $this->log($_GET);
        
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        		
		$token = TOKEN;
		$tmpArr = array($token, $timestamp, $nonce);
        // use SORT_STRING rule
		sort($tmpArr, SORT_STRING);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );
		
		if( $tmpStr == $signature ){
			return true;
		}else{
			return false;
		}
	}
}